<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>黄金矿工</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f5e8c9;
            font-family: 'Arial', sans-serif;
            color: #5a3e1f;
        }
        #gameContainer {
            position: relative;
            width: 800px;
            height: 850px;
            background-color: #8b5a2b;
            border: 10px solid #5a3e1f;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
            overflow: hidden;
        }
        canvas {
            background-color: #3a2a12;
            display: block;
        }
        #header {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 60px;
            background-color: #5a3e1f;
            color: #f8d347;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 20px;
            box-sizing: border-box;
            z-index: 10;
            font-weight: bold;
        }
        #gameTitle {
            font-size: 24px;
            text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.5);
        }
        #gameSubtitle {
            font-size: 14px;
            color: #fff;
        }
        #stats {
            display: flex;
            gap: 20px;
        }
        .stat {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .stat-label {
            font-size: 12px;
            color: #fff;
        }
        .stat-value {
            font-size: 18px;
            color: #f8d347;
        }
        #startScreen {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(90, 62, 31, 0.9);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            color: #f8d347;
            z-index: 20;
            text-align: center;
        }
        #instructions {
            background-color: rgba(139, 90, 43, 0.8);
            padding: 20px;
            border-radius: 10px;
            margin: 20px;
            max-width: 500px;
        }
        #itemValues {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 15px;
            margin: 20px 0;
        }
        .item {
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: rgba(248, 211, 71, 0.2);
            padding: 10px;
            border-radius: 5px;
            border: 1px solid #f8d347;
        }
        .item-icon {
            width: 30px;
            height: 30px;
            margin-bottom: 5px;
        }
        .item-name {
            font-size: 12px;
            color: #fff;
        }
        .item-value {
            font-size: 14px;
            font-weight: bold;
            color: #f8d347;
        }
        .button {
            margin: 10px;
            padding: 10px 20px;
            font-size: 16px;
            background-color: #f8d347;
            color: #5a3e1f;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
            transition: all 0.2s;
        }
        .button:hover {
            background-color: #ffdf5e;
            transform: scale(1.05);
        }
        #controls {
            display: flex;
            gap: 10px;
        }
        #gameOverScreen {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(90, 62, 31, 0.9);
            display: none;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            color: #f8d347;
            z-index: 20;
            text-align: center;
        }
        #gameOverMessage {
            font-size: 36px;
            margin-bottom: 20px;
            text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.5);
        }
        #finalScore {
            font-size: 24px;
            margin-bottom: 20px;
        }
        #levelInfo {
            font-size: 14px;
            margin-top: 5px;
            color: #fff;
        }
        #progressBar {
            width: 200px;
            height: 10px;
            background-color: #5a3e1f;
            border-radius: 5px;
            margin: 5px 0;
            overflow: hidden;
        }
        #progressFill {
            height: 100%;
            background-color: #f8d347;
            width: 0%;
            transition: width 0.3s;
        }
        .chart-container {
            width: 700px;
            height: 200px;
            margin: 10px auto;
        }
    </style>
</head>
<body>
    <div id="gameContainer">
        <div id="header">
            <div>
                <div id="gameTitle">黄金矿工</div>
                <div id="gameSubtitle">挖掘黄金，成为最富有的矿工！</div>
            </div>
            <div id="stats">
                <div class="stat">
                    <div class="stat-label">当前关分数</div>
                    <div class="stat-value" id="score">0</div>
                    <div id="levelInfo" class="stat-label">目标: 0 / 0 (第1关/共5关)</div>
                </div>
                <div class="stat">
                    <div class="stat-label">时间</div>
                    <div class="stat-value" id="time">60s</div>
                    <div id="progressBar">
                        <div id="progressFill"></div>
                    </div>
                </div>
                <div class="stat">
                    <div class="stat-label">总分数</div>
                    <div class="stat-value" id="totalScore">0</div>
                </div>
            </div>
        </div>
        <canvas id="gameCanvas" width="800" height="540"></canvas>
        
        <div id="startScreen">
            <h1>黄金矿工</h1>
            <div id="instructions">
                <h3>游戏说明</h3>
                <p>- 点击屏幕或按空格键发射爪子抓取黄金和钻石</p>
                <p>- 不同物品价值不同，抓取时间也不同</p>
                <p>- 石头没有价值，抓取会浪费时间</p>
                <p>- 每关有时间限制，达到目标分数即可通关</p>
                <p>- 共有5个关卡，难度会逐渐增加</p>
                
                <h3>物品价值</h3>
                <div id="itemValues">
                    <div class="item">
                        <div class="item-icon" style="background-color: #f8d347; border-radius: 50%; width: 20px; height: 20px;"></div>
                        <div class="item-name">小金块</div>
                        <div class="item-value">50分</div>
                    </div>
                    <div class="item">
                        <div class="item-icon" style="background-color: #f8d347; border-radius: 50%; width: 30px; height: 30px;"></div>
                        <div class="item-name">中金块</div>
                        <div class="item-value">100分</div>
                    </div>
                    <div class="item">
                        <div class="item-icon" style="background-color: #f8d347; border-radius: 50%; width: 40px; height: 40px;"></div>
                        <div class="item-name">大金块</div>
                        <div class="item-value">200分</div>
                    </div>
                    <div class="item">
                        <div class="item-icon" style="background-color: #b9f2ff; clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);"></div>
                        <div class="item-name">钻石</div>
                        <div class="item-value">300分</div>
                    </div>
                    <div class="item">
                        <div class="item-icon" style="background-color: #999; border-radius: 50%;"></div>
                        <div class="item-name">石头</div>
                        <div class="item-value">0分</div>
                    </div>
                </div>
            </div>
            <div id="controls">
                <button class="button" id="startButton">开始游戏</button>
                <button class="button" id="pauseButton" disabled>暂停游戏</button>
            </div>
        </div>
        
        <div id="gameOverScreen">
            <div id="gameOverMessage"></div>
            <div id="finalScore"></div>
            <div class="chart-container" id="scoreChart"></div>
            <div class="chart-container" id="oreChart"></div>
            <button class="button" id="restartButton">再来一局</button>
            <button class="button" id="nextLevelButton" style="display: none;">进入下一关</button>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.3/echarts.min.js"></script>
    <script>
        // 游戏常量
        const GAME_WIDTH = 800;
        const GAME_HEIGHT = 540;
        const HOOK_SPEED = 5;
        const RETURN_SPEED = 3;
        const GAME_DURATION = 60; // 60秒
        const TARGET_SCORE_PER_LEVEL = [300, 500, 800, 1200, 1800]; // 每关目标分数
        const TOTAL_LEVELS = TARGET_SCORE_PER_LEVEL.length;
        const MINER_X = GAME_WIDTH / 2;
        const MINER_Y = 80;
        
        // 游戏变量
        let score = 0; // 当前关分数
        let totalScore = 0; // 总分数
        let timeLeft = GAME_DURATION;
        let currentLevel = 1;
        let gameRunning = false;
        let gamePaused = false;
        let gameOver = false;
        let animationId = null;
        let lastTime = 0;
        let hookSwingDirection = 1;
        let hookSwingSpeed = 0.02;
        let hookMaxSwingAngle = Math.PI / 3;  
        let lastUpdateTime = 0;
        let levelScores = []; // 记录每关得分
        let collectedOres = []; // 记录已收集的矿石
        
        // 获取DOM元素
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const scoreElement = document.getElementById('score');
        const totalScoreElement = document.getElementById('totalScore');
        const timeElement = document.getElementById('time');
        const levelInfoElement = document.getElementById('levelInfo');
        const progressFill = document.getElementById('progressFill');
        const startScreen = document.getElementById('startScreen');
        const gameOverScreen = document.getElementById('gameOverScreen');
        const gameOverMessage = document.getElementById('gameOverMessage');
        const finalScore = document.getElementById('finalScore');
        const startButton = document.getElementById('startButton');
        const pauseButton = document.getElementById('pauseButton');
        const restartButton = document.getElementById('restartButton');
        const nextLevelButton = document.getElementById('nextLevelButton');
        
        // ECharts 实例
        const scoreChart = echarts.init(document.getElementById('scoreChart'));
        const oreChart = echarts.init(document.getElementById('oreChart'));

        // 游戏对象
        const miner = {
            x: MINER_X,
            y: MINER_Y,
            radius: 25
        };

        const hook = {
            x: miner.x,
            y: miner.y + miner.radius,
            length: 0,
            maxLength: 400,
            angle: 0,
            speed: HOOK_SPEED,
            state: 'swinging', // 'swinging', 'shooting', 'returning', 'pulling'
            target: null
        };

        // 矿石类型定义
        const oreTypes = [
            { type: 'smallGold', value: 50, radius: 20, weight: 1, color: '#f8d347', name: '小金块' },
            { type: 'mediumGold', value: 100, radius: 30, weight: 2, color: '#f8d347', name: '中金块' },
            { type: 'largeGold', value: 200, radius: 40, weight: 3, color: '#f8d347', name: '大金块' },
            { type: 'diamond', value: 300, radius: 15, weight: 0.5, color: '#b9f2ff', name: '钻石' },
            { type: 'stone', value: 0, radius: 25, weight: 4, color: '#999', name: '石头' }
        ];

        // 矿石数组
        let ores = [];

        // 初始化游戏
        function initGame() {
            score = 0;
            totalScore = 0;
            timeLeft = GAME_DURATION;
            currentLevel = 1;
            gameRunning = true;
            gamePaused = false;
            gameOver = false;
            levelScores = [];
            collectedOres = [];
            
            // 重置钩子状态
            hook.x = miner.x;
            hook.y = miner.y + miner.radius;
            hook.length = 0;
            hook.angle = 0;
            hook.state = 'swinging';
            hook.target = null;
            
            // 生成矿石
            generateOres();
            
            // 更新UI
            updateUI();
            
            // 隐藏开始和结束屏幕
            startScreen.style.display = 'none';
            gameOverScreen.style.display = 'none';
            
            // 初始化图表
            initScoreChart();
            initOreChart();
            
            // 开始游戏循环
            if (animationId) {
                cancelAnimationFrame(animationId);
            }
            lastTime = performance.now();
            lastUpdateTime = performance.now();
            animationId = requestAnimationFrame(gameLoop);
        }

        // 生成矿石
        function generateOres() {
            ores = [];
            
            // 根据关卡决定矿石数量 (5 + 关卡数 × 3)
            const oreCount = 5 + currentLevel * 3;
            
            // 计算每种矿石的生成概率
            const probabilities = calculateOreProbabilities();
            
            Array.from({ length: oreCount }).forEach(() => {
                // 根据概率随机选择矿石类型
                const rand = Math.random();
                let cumulativeProb = 0;
                let typeIndex = 0;
                
                for (let j = 0; j < probabilities.length; j++) {
                    cumulativeProb += probabilities[j];
                    if (rand < cumulativeProb) {
                        typeIndex = j;
                        break;
                    }
                }
                
                const type = oreTypes[typeIndex];
                
                // 确保矿石不会重叠
                let x, y;
                let validPosition = false;
                
                while (!validPosition) {
                    x = 100 + Math.random() * (GAME_WIDTH - 200);
                    y = 150 + Math.random() * (GAME_HEIGHT - 200);
                    validPosition = true;
                    
                    // 使用forEach检查是否与其他矿石重叠
                    ores.forEach(ore => {
                        const dx = ore.x - x;
                        const dy = ore.y - y;
                        const distance = Math.sqrt(dx * dx + dy * dy);
                        
                        if (distance < ore.radius + type.radius + 10) {
                            validPosition = false;
                        }
                    });
                }
                
                ores.push({
                    type: type.type,
                    value: type.value,
                    radius: type.radius,
                    weight: type.weight,
                    color: type.color,
                    name: type.name,
                    x: x,
                    y: y,
                    collected: false
                });
            });
            
            console.log(`第${currentLevel}关生成矿石数量: ${ores.length}`);
        }

        // 计算矿石生成概率
        function calculateOreProbabilities() {
            // 基础概率
            let probabilities = [0.3, 0.25, 0.15, 0.1, 0.2]; // 小金, 中金, 大金, 钻石, 石头
            
            // 随着关卡增加，减少石头概率，增加高价值物品概率
            const levelFactor = (currentLevel - 1) / (TOTAL_LEVELS - 1);
            
            // 调整概率
            probabilities[4] = Math.max(0.05, probabilities[4] - levelFactor * 0.15); // 石头
            probabilities[3] = probabilities[3] + levelFactor * 0.1; // 钻石
            probabilities[2] = probabilities[2] + levelFactor * 0.05; // 大金
            
            // 确保概率总和为1
            const sum = probabilities.reduce((a, b) => a + b, 0);
            return probabilities.map(p => p / sum);
        }

        // 游戏主循环
        function gameLoop(timestamp) {
            if (!gameRunning || gamePaused) return;
            
            // 计算时间增量
            const deltaTime = (timestamp - lastTime) / 1000;
            lastTime = timestamp;
            
            // 每16ms更新一次游戏状态(约60fps)
            if (timestamp - lastUpdateTime >= 16) {
                updateGameState(timestamp);
                lastUpdateTime = timestamp;
            }
            
            // 渲染游戏
            render();
            
            // 继续循环
            animationId = requestAnimationFrame(gameLoop);
        }

        // 更新游戏状态
        function updateGameState(timestamp) {
            // 更新时间
            if (!gameOver) {
                const timeDelta = (timestamp - lastUpdateTime) / 1000;
                timeLeft = Math.max(0, timeLeft - timeDelta);
                
                // 更新进度条
                progressFill.style.width = `${(timeLeft / GAME_DURATION) * 100}%`;
                
                if (timeLeft <= 0) {
                    timeLeft = 0;
                    gameOver = true;
                    endGame(false);
                    return;
                }
                
                // 更新UI时间显示
                timeElement.textContent = `${Math.ceil(timeLeft)}s`;
            }
            
            // 更新钩子状态
            switch (hook.state) {
                case 'swinging':
                    // 钩子摆动逻辑
                    hook.angle += hookSwingSpeed * hookSwingDirection;
                    
                    // 改变摆动方向当达到最大角度
                    if (Math.abs(hook.angle) > hookMaxSwingAngle) {
                        hookSwingDirection *= -1;
                        hook.angle = Math.sign(hook.angle) * hookMaxSwingAngle;
                    }
                    
                    // 更新钩子位置
                    hook.x = miner.x + Math.sin(hook.angle) * miner.radius;
                    hook.y = miner.y + miner.radius + Math.cos(hook.angle) * miner.radius;
                    break;
                    
                case 'shooting':
                    hook.length += hook.speed;
                    hook.x = miner.x + Math.sin(hook.angle) * hook.length;
                    hook.y = miner.y + miner.radius + Math.cos(hook.angle) * hook.length;
                    
                    // 检查是否达到最大长度
                    if (hook.length >= hook.maxLength) {
                        hook.state = 'returning';
                    }
                    
                    // 检查是否碰到矿石
                    checkCollision();
                    break;
                    
                case 'returning':
                    hook.length -= RETURN_SPEED;
                    hook.x = miner.x + Math.sin(hook.angle) * hook.length;
                    hook.y = miner.y + miner.radius + Math.cos(hook.angle) * hook.length;
                    
                    // 检查是否回到起点
                    if (hook.length <= 0) {
                        hook.length = 0;
                        hook.state = 'swinging';
                        hook.target = null;
                    }
                    break;
                    
                case 'pulling':
                    if (hook.target) {
                        // 根据重量调整拉回速度
                        const pullSpeed = RETURN_SPEED / hook.target.weight;
                        hook.length -= pullSpeed;
                        
                        // 更新钩子和目标位置
                        hook.x = miner.x + Math.sin(hook.angle) * hook.length;
                        hook.y = miner.y + miner.radius + Math.cos(hook.angle) * hook.length;
                        
                        hook.target.x = hook.x;
                        hook.target.y = hook.y;
                        
                        // 检查是否回到起点
                        if (hook.length <= 0) {
                            // 增加分数
                            score += hook.target.value;
                            
                            // 记录收集的矿石
                            collectedOres.push({
                                type: hook.target.type,
                                value: hook.target.value,
                                level: currentLevel
                            });
                            
                            updateUI();
                            updateOreChart();
                            
                            // 检查是否达到目标分数
                            if (score >= TARGET_SCORE_PER_LEVEL[currentLevel - 1]) {
                                levelScores.push(score);
                                levelComplete();
                                return;
                            }
                            
                            // 标记矿石为已收集
                            hook.target.collected = true;
                            
                            // 重置钩子状态
                            hook.length = 0;
                            hook.state = 'swinging';
                            hook.target = null;
                        }
                    } else {
                        hook.state = 'returning';
                    }
                    break;
            }
        }

        // 检查碰撞
        function checkCollision() {
            if (hook.state !== 'shooting') return;
            
            // 使用forEach检查碰撞
            ores.forEach(ore => {
                if (ore.collected) return;
                
                const dx = ore.x - hook.x;
                const dy = ore.y - hook.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                if (distance < ore.radius + 5) { // 5是钩子的"碰撞半径"
                    // 捕获矿石
                    hook.state = 'pulling';
                    hook.target = ore;
                    
                    // 如果是石头，惩罚时间
                    if (ore.type === 'stone') {
                        timeLeft = Math.max(1, timeLeft - 5);
                        updateUI();
                    }
                }
            });
        }

        // 关卡完成
        function levelComplete() {
            console.log(`关卡完成: 第${currentLevel}关`);
            
            // 更新总分数
            totalScore += score;
            
            // 标记矿石为已收集
            if (hook.target) {
                hook.target.collected = true;
            }
            
            // 重置钩子状态
            hook.state = 'swinging';
            hook.length = 0;
            hook.target = null;
            
            // 更新图表
            updateScoreChart();
            updateOreChart();
            
            // 检查是否还有更多关卡
            if (currentLevel < TOTAL_LEVELS) {
                // 显示关卡过渡信息
                gamePaused = true;
                gameOverScreen.style.display = 'flex';
                gameOverMessage.textContent = `恭喜通过第${currentLevel}关！`;
                finalScore.textContent = `本关得分: ${score} | 总得分: ${totalScore} | 即将开始第${currentLevel+1}关`;
                
                // 显示"下一关"按钮
                nextLevelButton.style.display = 'block';
                nextLevelButton.onclick = () => {
                    // 进入下一关前重置当前关分数
                    score = 0;
                    currentLevel++;
                    timeLeft = GAME_DURATION;
                    generateOres();
                    updateUI();
                    
                    gamePaused = false;
                    gameOverScreen.style.display = 'none';
                    nextLevelButton.style.display = 'none';
                    lastTime = performance.now();
                    lastUpdateTime = performance.now();
                    animationId = requestAnimationFrame(gameLoop);
                };
                
                // 3秒后自动继续
                setTimeout(() => {
                    if (gamePaused) { // 确保用户没有手动点击按钮
                        // 进入下一关前重置当前关分数
                        score = 0;
                        currentLevel++;
                        timeLeft = GAME_DURATION;
                        generateOres();
                        updateUI();
                        
                        gamePaused = false;
                        gameOverScreen.style.display = 'none';
                        nextLevelButton.style.display = 'none';
                        lastTime = performance.now();
                        lastUpdateTime = performance.now();
                        animationId = requestAnimationFrame(gameLoop);
                    }
                }, 3000);
            } else {
                // 游戏通关
                totalScore += score; // 加上最后一关的分数
                levelScores.push(score);
                endGame(true);
            }
        }

        // 渲染游戏
        function render() {
            // 清空画布
            ctx.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
            
            // 绘制背景 - 矿井背景
            ctx.fillStyle = '#3a2a12';
            ctx.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
            
            // 使用forEach绘制矿石
            ores.forEach(ore => {
                if (ore.collected) return;
                
                ctx.fillStyle = ore.color;
                ctx.beginPath();
                ctx.arc(ore.x, ore.y, ore.radius, 0, Math.PI * 2);
                ctx.fill();
                
                // 特殊形状
                if (ore.type === 'diamond') {
                    ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
                    ctx.beginPath();
                    ctx.moveTo(ore.x, ore.y - ore.radius * 0.7);
                    ctx.lineTo(ore.x + ore.radius * 0.5, ore.y);
                    ctx.lineTo(ore.x, ore.y + ore.radius * 0.7);
                    ctx.lineTo(ore.x - ore.radius * 0.5, ore.y);
                    ctx.closePath();
                    ctx.fill();
                } else if (ore.type === 'stone') {
                    // 石头纹理
                    ctx.fillStyle = '#777';
                    ctx.beginPath();
                    ctx.arc(ore.x - ore.radius * 0.3, ore.y - ore.radius * 0.3, ore.radius * 0.2, 0, Math.PI * 2);
                    ctx.fill();
                    ctx.beginPath();
                    ctx.arc(ore.x + ore.radius * 0.2, ore.y + ore.radius * 0.2, ore.radius * 0.15, 0, Math.PI * 2);
                    ctx.fill();
                }
            });
            
            // 绘制矿工
            ctx.fillStyle = '#5a3e1f';
            ctx.beginPath();
            ctx.arc(miner.x, miner.y, miner.radius, 0, Math.PI * 2);
            ctx.fill();
            
            // 绘制矿工面部
            ctx.fillStyle = '#8b5a2b';
            ctx.beginPath();
            ctx.arc(miner.x, miner.y, miner.radius * 0.7, 0, Math.PI * 2);
            ctx.fill();
            
            // 绘制矿工眼睛
            ctx.fillStyle = '#000';
            ctx.beginPath();
            ctx.arc(miner.x - miner.radius * 0.3, miner.y - miner.radius * 0.1, miner.radius * 0.1, 0, Math.PI * 2);
            ctx.arc(miner.x + miner.radius * 0.3, miner.y - miner.radius * 0.1, miner.radius * 0.1, 0, Math.PI * 2);
            ctx.fill();
            
            // 绘制矿工帽子
            ctx.fillStyle = '#3a2a12';
            ctx.beginPath();
            ctx.arc(miner.x, miner.y - miner.radius * 0.5, miner.radius * 0.8, 0, Math.PI, true);
            ctx.fill();
            
            // 绘制钩绳
            ctx.strokeStyle = '#5a3e1f';
            ctx.lineWidth = 3;
            ctx.beginPath();
            ctx.moveTo(miner.x, miner.y + miner.radius);
            ctx.lineTo(hook.x, hook.y);
            ctx.stroke();
            
            // 绘制钩子
            ctx.fillStyle = '#333';
            ctx.beginPath();
            ctx.arc(hook.x, hook.y, 8, 0, Math.PI * 2);
            ctx.fill();
            
            // 绘制钩子开口
            if (hook.state === 'swinging' || hook.state === 'shooting') {
                ctx.strokeStyle = '#666';
                ctx.lineWidth = 2;
                ctx.beginPath();
                ctx.arc(hook.x, hook.y, 6, Math.PI * 0.2, Math.PI * 0.8);
                ctx.stroke();
                ctx.beginPath();
                ctx.arc(hook.x, hook.y, 6, Math.PI * 1.2, Math.PI * 1.8);
                ctx.stroke();
            } else if (hook.state === 'pulling' && hook.target) {
                // 绘制抓取状态
                ctx.fillStyle = '#666';
                ctx.beginPath();
                ctx.moveTo(hook.x, hook.y - 6);
                ctx.lineTo(hook.x + 6, hook.y);
                ctx.lineTo(hook.x, hook.y + 6);
                ctx.lineTo(hook.x - 6, hook.y);
                ctx.closePath();
                ctx.fill();
            }
        }

        // 更新UI
        function updateUI() {
            scoreElement.textContent = score;
            totalScoreElement.textContent = totalScore;
            timeElement.textContent = `${Math.ceil(timeLeft)}s`;
            levelInfoElement.textContent = `目标: ${score} / ${TARGET_SCORE_PER_LEVEL[currentLevel-1]} (第${currentLevel}关/共${TOTAL_LEVELS}关)`;
            
            // 更新进度条颜色
            const timeRatio = timeLeft / GAME_DURATION;
            if (timeRatio < 0.3) {
                progressFill.style.backgroundColor = '#ff5555';
            } else if (timeRatio < 0.6) {
                progressFill.style.backgroundColor = '#ffaa00';
            } else {
                progressFill.style.backgroundColor = '#f8d347';
            }
        }

        // 结束游戏
        function endGame(success) {
            gameRunning = false;
            gameOver = true;
            
            gameOverMessage.textContent = success ? '恭喜通关！' : '时间到，游戏结束！';
            finalScore.textContent = `最终总分数: ${totalScore}`;
            
            // 更新图表
            updateScoreChart();
            updateOreChart();
            
            gameOverScreen.style.display = 'flex';
            nextLevelButton.style.display = 'none';
        }

        // 暂停游戏
        function togglePause() {
            if (gameOver) return;
            
            gamePaused = !gamePaused;
            pauseButton.textContent = gamePaused ? '继续游戏' : '暂停游戏';
            
            if (!gamePaused && gameRunning) {
                lastTime = performance.now();
                lastUpdateTime = performance.now();
                animationId = requestAnimationFrame(gameLoop);
            }
        }

        // --------------------- ECharts 图表函数 --------------------- //

        // 初始化得分趋势图
        function initScoreChart() {
            const option = {
                title: {
                    text: '得分趋势',
                    left: 'center',
                    textStyle: {
                        color: '#f8d347',
                        fontSize: 16
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        crossStyle: {
                            color: '#999'
                        }
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: levelScores.map((_, i) => `第${i+1}关`),
                    axisLabel: {
                        color: '#fff'
                    }
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        color: '#fff'
                    }
                },
                series: [{
                    name: '得分',
                    type: 'bar',
                    data: levelScores,
                    itemStyle: {
                        color: '#f8d347'
                    }
                }]
            };
            
            scoreChart.setOption(option);
        }

        // 更新得分趋势图
        function updateScoreChart() {
            scoreChart.setOption({
                xAxis: {
                    data: levelScores.map((_, i) => `第${i+1}关`)
                },
                series: [{
                    data: levelScores
                }]
            });
        }

        // 初始化矿石统计图表
        function initOreChart() {
            const option = {
                title: {
                    text: '收集矿石统计',
                    left: 'center',
                    textStyle: {
                        color: '#f8d347',
                        fontSize: 16
                    }
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c}个'
                },
                legend: {
                    orient: 'horizontal',
                    top: 'bottom',
                    textStyle: {
                        color: '#fff'
                    }
                },
                series: [{
                    name: '矿石',
                    type: 'pie',
                    radius: '50%',
                    data: oreTypes.map(type => ({
                        value: 0,
                        name: type.name,
                        itemStyle: {
                            color: type.color
                        }
                    })),
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }]
            };
            
            oreChart.setOption(option);
        }

        // 更新矿石统计图表
        function updateOreChart() {
            // 计算每种矿石的数量
            const oreCounts = oreTypes.reduce((acc, type) => {
                acc[type.type] = 0;
                return acc;
            }, {});
            
            collectedOres.forEach(ore => {
                oreCounts[ore.type] = (oreCounts[ore.type] || 0) + 1;
            });
            
            oreChart.setOption({
                series: [{
                    data: oreTypes.map(type => ({
                        value: oreCounts[type.type] || 0,
                        name: type.name,
                        itemStyle: {
                            color: type.color
                        }
                    }))
                }]
            });
        }

        // 事件监听
        canvas.addEventListener('click', (e) => {
            if (!gameRunning || gamePaused || gameOver) return;
            
            if (hook.state === 'swinging') {
                // 发射钩子
                hook.state = 'shooting';
            }
        });

        document.addEventListener('keydown', (e) => {
            if (e.code === 'Space') {
                e.preventDefault();
                if (!gameRunning || gamePaused || gameOver) return;
                
                if (hook.state === 'swinging') {
                    // 发射钩子
                    hook.state = 'shooting';
                }
            } else if (e.code === 'Escape') {
                if (gameRunning && !gameOver) {
                    togglePause();
                }
            }
        });

        startButton.addEventListener('click', initGame);
        pauseButton.addEventListener('click', togglePause);
        restartButton.addEventListener('click', initGame);

        // 初始显示开始屏幕
        startScreen.style.display = 'flex';
    </script>
</body>
</html>    